/**
 *
 * 课程创建、编辑界面JS调用
 */
//验证课程名称
function checkCourseName() {
	var name = $("input[name='name']");
	if (name.val() == '') {
		showMessageTip('name', '课程名称不能为空', 'error');
		//name.focus();
		return false;
	}
	
	var str_len = getStrActualLen(name.val());
	if (str_len < 4 || str_len > 60) {
		showMessageTip('name', '限定2-30个汉字或者4-60字符', 'error');
		//name.focus();
		return false;
	}
	
	if (/[<>]/.test(name.val())) {
		showMessageTip('name', '课程名称不能使用HTML标签代码', 'error');
		//name.focus();
		return false;
	}
	
	showMessageTip('name', '', 'success');
	return true;
}

//验证课程价格
function checkCost() {
	var cost = $("input[name='cost']");
	if (cost.val() == '') {
		showMessageTip('cost', '请填写课程价格', 'error');
		
		return false;
	}
	
	if (!/^\d+\.?[\d]{0,2}$/.test(cost.val())){
		showMessageTip('cost', '只允许格式为0.00的数字', 'error');
		
		return false;
	}
	
	var course_cost = parseFloat(cost.val());
	if (course_cost < 0.00) {
		showMessageTip('cost', '价格不能小于0.00元', 'error');
		return false;
	}
	if (course_cost > 1000000) {
		showMessageTip('cost', '价格不能大于1000000元', 'error');
		return false;
	}
	
	showMessageTip('cost', '', 'success');
	return true;
}

function checkSingleBuy(){
	var type = $("input:radio[name='singleBuy']:checked").val();
	if(type == 2){
		var cost = $("#singlePrice").val();
		if(cost == ''){
			showMessageTip('singlePrice', '请填写单节课程价格', 'error');
			return false;
		}
		if (!/^\d+\.?[\d]{0,2}$/.test(cost)){
			showMessageTip('singlePrice', '只允许格式为0.00的数字', 'error');
			return false;
		}
		
		var course_cost = parseFloat(cost);
		if (course_cost < 0.00) {
			showMessageTip('singlePrice', '价格不能小于0.00元', 'error');
			return false;
		}
		if (course_cost > 1000000) {
			showMessageTip('singlePrice', '价格不能大于1000000元', 'error');
			return false;
		}
		
		showMessageTip('singlePrice', '', 'success');
		return true;
	}else{
		showMessageTip('singlePrice', '', 'success');
		return true;
	}
}

//验证课时
function checkCourseHours() {
	var hours = $("input[name='hours']");
	if (hours.val() == '') {
		showMessageTip('hours', '请填写课程总课时', 'error');
		//hours.focus();
		return false;
	}
	
	var course_hours = parseInt(hours.val());
	if (!/^\d{0,4}$/.test(hours.val()) || course_hours < 1 || course_hours > 1000){
		showMessageTip('hours', '课时为1-1000的整数', 'error');
		//hours.focus();
		return false;
	}
	
	showMessageTip('hours', '', 'success');
	return true;
}

//验证课程结束时间
function checkPayEndTime() {
	var payendtime = $("input[name='payendtime']");
	if (!/^\d{4}-\d{2}-\d{2}$/.test(payendtime.val())) {
		showMessageTip('payendtime', '请选择课程有效期', 'error');
		//payendtime.focus();
		return false;
	}
	var nowdate = new Date();
	if(dateCompare(payendtime.val(), nowdate.getFullYear()+'-'+(nowdate.getMonth()+1)+'-'+nowdate.getDate())){
		showMessageTip('payendtime', '结束时间不能小于当前时间', 'error');
		return false;
	}
	showMessageTip('payendtime', '', 'success');
	return true;
}

function checkExpireTime() {
	var expiretime = $("input[name='expiretime']");
	var expiretimevalue = expiretime.val();
	if (expiretimevalue == ''){
		showMessageTip('expiretime', '请填写有效期', 'error');
		return false;
	}
	if (!/^\d*$/.test(expiretimevalue)) {
		showMessageTip('expiretime', '有效期格式错误', 'error');
		//expiretime.focus();
		return false;
	}
	if ( expiretimevalue < 30 || expiretimevalue > 3650){
		showMessageTip('expiretime', '有效期不在限定范围内', 'error');
		return false;
	}
	showMessageTip('expiretime', '', 'success');
	return true;
}

function dateCompare(startStr,endStr){
	var d1, d2, s, arr, arr1, arr2;
	if(startStr.length > 10){
		arr = startStr.split(" ");
		arr1 = arr[0].split("-");
		arr2 = arr[1].split(":");
		d1 = new Date(arr1[0], arr1[1] - 1, arr1[2], arr2[0], arr2[1], arr2[2]);
	}else{
		arr = startStr.split("-");
		d1 = new Date(arr[0], arr[1], arr[2]);
	}
	if(endStr.length > 10){
		arr = endStr.split(" ");
		arr1 = arr[0].split("-");
		arr2 = arr[1].split(":");
		d2 = new Date(arr1[0], arr1[1] - 1, arr1[2], arr2[0], arr2[1], arr2[2]);
	}else{
		arr = endStr.split("-");
		d2 = new Date(arr[0], arr[1], arr[2]);
	}
	s = d2 - d1 ;
	if(s <= 0){
		return false;
	}
	return true;
}

//验证购买人数
function checkStudentLimit() {
	var limit = $("input[name='studentlimit']");
	var student_limit = parseInt(limit.val());
	if(limit.val == ''){
		return false;
	}else if (!/^\d{1,7}$/.test(limit.val()) || student_limit < 1 || student_limit > 1000000) {
		showMessageTip('studentlimit', '人数需为1-1000000的整数', 'error');
		//limit.focus();
		return false;
	}
	showMessageTip('studentlimit', '', 'success');
	return true;
}

//验证教室容量
function checkClassroomCapacity() {
	var element = $("input[name='classroomcapacity']");
	if (element.val() == '') {
		showMessageTip('classroomcapacity', '请填写教室容量', 'error');
		//element.focus();
		return false;
	}
	
	var capacity = parseInt(element.val());
	if (!/^\d{0,10}$/.test(element.val()) || capacity < 1 || capacity > ClassroomLimit){
		showMessageTip('classroomcapacity', '教室容量为1-'+ClassroomLimit+'的整数', 'error');
		//element.focus();
		return false;
	}
	
	showMessageTip('classroomcapacity', '', 'success');
	return true;
}

//验证课程介绍
function checkBrief(){
	var element = $("#brief");
	if(element.val() == ''){
		showMessageTip('brief', '请填写课程描述', 'error');
		element.focus();
		return false;
	}
	if(element.val().length > 20000){
		showMessageTip('brief', '课程介绍内容太长', 'error');
		element.focus();
		return false;
	}

	showMessageTip('brief', '', 'success');
	return true;
}

//验证课程封面
function checkCover(){
	var element = $("#cover");
	if(element.val() == ''){
		showMessageTip('cover', '请上传课程封面', 'error');
		element.focus();
		return false;
	}
	
	showMessageTip('cover', '', 'success');
	return true;
}

//验证课程回放时间
function checkVodExpires(){
	var element = $("#vodExpires");
	var vodExpires = parseInt(element.val());
	if (!/^\d{1,3}$/.test(element.val()) || vodExpires == '' || vodExpires < 15 || vodExpires > 500) {
		showMessageTip('vodExpires', '需为15-500的整数', 'error');
		return false;
	}
	showMessageTip('vodExpires', '', 'success');
	return true;
}

//验证课程老师信息
function checkCourseTeacher(){
	var teachernum = 5;
	var teacherPostArr = '';
	var submitteachernum = 0;
	for(var i = 1; i <= teachernum; i++){
		if(($('#teacherphoto'+i).attr('val') != '') || ($('#teachername'+i).val() != '') || ($('#teacherbrief'+i).val() != '')){
			var teacherphoto = $('#teacherphoto'+i).attr('val');
			
			if(teacherphoto == ''){
				showMessageTip('teacherbrief'+i, '请上传老师头像', 'error');
				return false;
			} else {
				showMessageTip('teacherbrief'+i, '', 'success');
			}		
			
			var teachername = $('#teachername'+i).val();
			var cteachername = checkName(teachername, 1, 40);
			if(cteachername == 2){ 
				showMessageTip('teachername'+i, '请填写老师姓名', 'error');
				return false;
			} else if(cteachername == 3){
				showMessageTip('teachername'+i, '输入长度请控制在1-20汉字', 'error');
				return false;
			} else {
				showMessageTip('teachername'+i, '', 'success');
			}
			var teacherbrief = $('#teacherbrief'+i).val();
			var cteacherbrief = checkName(teacherbrief, 1, 600);
			if(cteacherbrief == 2){
				showMessageTip('teacherbrief'+i, '请填写老师的简介', 'error');
				return false;
			} else if(cteacherbrief == 3){
				showMessageTip('teacherbrief'+i, '输入长度请控制在1-300汉字', 'error');
				return false;
			} else {
				showMessageTip('teacherbrief'+i, '', 'success');
			}
			teacherPostArr += '&teacherphoto'+i+'='+encodeURIComponent(teacherphoto)+'&teachername'+i+'='+encodeURIComponent(teachername)+'&teacherbrief'+i+'='+encodeURIComponent(teacherbrief);	
			submitteachernum++;
		}
	}
	
 	if(teacherPostArr != ''){
		teacherPostArr += '&teachernum='+submitteachernum;
		return teacherPostArr;
	} else {
		
		return teacherPostArr;
	}
}

//验证课程适合人群
function checkPeople(){
	var people = $('#people').val();
	var cpeople = checkName(people, 0, 20);
	if(cpeople == 3){
		showMessageTip('people', '输入长度请控制在10汉字以内', 'error');
		return false;
	} else {
		showMessageTip('people', '', 'success');
		return true;
	}
}
//验证课程学到什么
function checkKnowledge(){
	var knowledge = $('#knowledge').val();
	var cknowledge = checkName(knowledge, 0, 400);
	if(cknowledge == 3){
		showMessageTip('knowledge', '输入长度请控制在200汉字以内', 'error');
		return false;
	} else {
		showMessageTip('knowledge', '', 'success');
		return true;
	}
}

var shine = '',
	tid = 0,
	shineStep = 0;
var ErrorShine = function(dom){
	var scrollTop = dom.offset();
	$("body,html").animate({
		scrollTop:(scrollTop.top-50)
	},0);
	shineStep = 0;
	shine = function(){
		if(shineStep%2 == 0){
			dom.removeClass('form_text_error');
		}else{
			dom.addClass('form_text_error');
			if(shineStep == 3){
				window.clearInterval(tid);
			}
		}
		shineStep++;
	}
	tid = setInterval('shine()', 500);	
}

var autoSaveBrief = function(){
	editor.sync();
	var content =  $("#brief").val();
	if(IsAuthorize > 0){
		var url = "/?mod=course&act=create&do=autoCacheBrief&authorize=1&sid="+SID;
	}else{
		var url = "/?mod=course&act=create&do=autoCacheBrief";
	}
	if(content != ''){
		$.ajax({
			url : url,
			type : "POST",
			async : true,
			dataType : "json",
			data : "brief="+encodeURIComponent(content),
			success : function(rs){
				if(rs.code > 0){
					$("#autoSaveTips").show().find("em").text(rs.data);
				}
			}
		});
	}
}

var restoreBrief = function(){
	if(IsAuthorize > 0){
		var url = "/?mod=course&act=create&do=getCacheBrief&authorize=1&sid="+SID+"&random="+Math.random();
	}else{
		var url = "/?mod=course&act=create&do=getCacheBrief&random="+Math.random();
	}
	$.getJSON(url, function(rs){
		if(rs.code > 0){
			editor.html(rs.data[1]);
			$("#autoSaveTips").hide();
		}
	})
}

//定时器标记
var runTag;

//编辑器
// var editor;
// KindEditor.ready(function(K) {
// 	editor = K.create('#brief', {
// 		resizeType : 1,
// 		allowPreviewEmoticons : false,
// 		allowImageUpload : true,
// 		uploadJson : KK._uploadImgUrl+"/?sid="+SID+"&type=4&json=1",
// 		filePostName : "userfile",
// 		newlineTag : "p",
// 		width : "755px",
// 		height : "420px",
// 		htmlTags : {
// 	        font : ['color', 'size', 'face', '.background-color'],
// 	        span : [
// 	                '.color', '.background-color', '.font-size', '.font-family', '.background',
// 	                '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
// 	        ],
// 	        table: [
// 	                'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
// 	                '.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
// 	                '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
// 	                '.width', '.height', '.border-collapse'
// 	        ],
// 	        'td,th': [
// 	                'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
// 	                '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
// 	                '.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
// 	        ],
// 	        a : ['href', 'target', 'name', 'class', 'data-courseid', 'data-sid', 'data-chatbind'],
// 	        embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
// 	        img : ['src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
// 	        'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [
// 	                'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
// 	                '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
// 	        ],
// 	        pre : ['class'],
// 	        hr : ['class', '.page-break-after'],
// 	        'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : []
// 		},
// 		items : ['source', '|', 'undo', 'redo', '|', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
// 			     'italic', 'underline', 'strikethrough', '|', 'justifyleft', 'justifycenter', 'justifyright',
// 		         'justifyfull', '|', 'indent', 'outdent', 'lineheight', '|',
// 		         'removeformat', 'clearhtml', 'quickformat', 'selectall', '|', 'multiimage', 'code', '|', 'link', 'unlink',
// 			     'print', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste'],
// 		afterChange : function() {
// 			K('#briefCount').html(this.count());
// 		},
// 		afterFocus : function(){
// 			showMessageTip('brief', '请详细介绍该课程的主要内容、特色、能解决学生什么问题等信息', 'notice');
// 			if (CourseID == false) {
// 				runTag = setInterval("autoSaveBrief();", 30000);
// 			}
// 		},
// 		afterBlur : function(){
// 			this.sync();
// 			checkBrief();
// 			if (CourseID == false) {
// 				clearInterval(runTag);
// 			}
// 		}
// 	});
// });

$(function(){
	
	$("#autoSaveBrief").click(function(){
		restoreBrief();
		checkBrief();
	})
	
	 $("input:radio[name='singleBuy']").click(function(){
		if($(this).val() == 2){
			$("#singlePrice").removeAttr('disabled').focus();
		}else{
			$("#singlePrice").val('').attr('disabled', true);
			showMessageTip('singlePrice', '', 'success');
		}
	 });
	
	$('#addteacher').click(function(){
		var hidden_teacher = $("div[id^='teacher']:hidden");
		if(hidden_teacher.length > 0){
			hidden_teacher.eq(0).show();
		} else {
			$.ckAlert({message : '最多添加5个老师'});
			return false;
		}
	});
	
	$('a.delteacher').click(function(){ 
		var num = $(this).attr('num');
		$('#teacher'+num).hide();
		$('#teacher'+num+' img').attr('src','http://res.ckimg.com/sites/www/v2/images/public/90f46d6963726f736b797065a502.jpg');
		$('#teacher'+num+' img').attr('val','');
		$('#teacher'+num+' input').val('');
		$('#teacher'+num+' textarea').val('');
		var teachernum = parseInt($('#addteacher').attr('num')) - 1;
		$('#addteacher').attr('num', teachernum);
		
	});
	
	$('#empty').click(function(){
		$('span.teacher-pic img').attr('src','http://res.ckimg.com/sites/www/v2/images/public/90f46d6963726f736b797065a502.jpg');
		$('span.teacher-pic img').attr('val','');
		$('div.teacher-info input').val('');
		$('div.teacher-info textarea').val('');
	});
	
	// if(CourseID === false){
	// 	$("#modifyCate").click(function(){
	// 		$("#cateid_tips_name").html('<img src="'+KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif" width="" height="" />');
			
	// 		editor.sync();
			
	// 		var name = $("#name").val(),
	// 			cost = $("#cost").val(),
	// 			cateid = $("#cateid").val(),
	// 			hours = $("#hours").val(),
	// 			expiretime = $("#expiretime").val(),
	// 			studentlimit = $("#studentlimit").val(),
	// 			classroomcapacity = $("#classroomcapacity").val(),
	// 			brief = $("#brief").val(),
	// 			cover = $("#cover").val(),
	// 			customParentType = $("#customParentType").val(),
	// 			customSubType = $("#customSubType").val(),
	// 			vodExpires = $("#vodExpires").val();
		
	// 		var cacheDataStr = ["name="+encodeURIComponent(name),
	// 	                   "cost="+encodeURIComponent(cost),
	// 	                   "hours="+encodeURIComponent(hours),
	// 	                   "expiretime="+encodeURIComponent(expiretime),
	// 	                   "studentlimit="+encodeURIComponent(studentlimit),
	// 	                   "classroomcapacity="+encodeURIComponent(classroomcapacity),
	// 	                   "brief="+encodeURIComponent(brief),
	// 	                   "cover="+encodeURIComponent(cover),
	// 	                   "customParentType="+encodeURIComponent(customParentType),
	// 	                   "customSubType="+encodeURIComponent(customSubType),
	// 	                   "vodExpires="+encodeURIComponent(vodExpires)].join('&');
	// 		if(IsAuthorize > 0){
 //    			var url = "/?mod=course&act=create&do=cacheBasic&authorize=1&sid="+SID+"&random="+Math.random();
 //    		}else{
 //    			var url = "/?mod=course&act=create&do=cacheBasic&random="+Math.random();
 //    		}	
	// 		$.ajax({
	// 			url : url,
	// 			type : "post",
	// 			data : cacheDataStr,
	// 			async : true,
	// 			dataType : 'json',
	// 			success : function(rs){
	// 				if(rs.code > 0){
	// 					$("#cateid_tips_name").html('');
	// 					if(IsAuthorize > 0){
	// 						document.location = '/?mod=course&act=create&do=cate&authorize=1&sid='+SID+'&cateid='+cateid;
	// 					}else{
	// 						document.location = '/?mod=course&act=create&do=cate&cateid='+cateid;
	// 					}
	// 				}
	// 			}
	// 		});
	// 		return false;
	// 	});
	// }else{
	// 	$("#modifyCate").click(function(){
	// 		var cateid = $("#cateid").val();
	// 		if(IsAuthorize > 0){
	// 			document.location = '/?mod=course&act=create&do=cate&authorize=1&sid='+SID+'&courseid='+CourseID+'&cateid='+cateid;
	// 		}else{
	// 			document.location = '/?mod=course&act=create&do=cate&courseid='+CourseID+'&cateid='+cateid;
	// 		}
	// 		return false;
	// 	});
	// }
	
	// $("#uploadTeacher1").uploadify3({
 //        height			: '30',
 //        swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
 //        uploader		: KK._uploadImgUrl+"/?sid="+SID+"&type=2&json=1",
 //        width			: '128',
 //        buttonCursor	: '',
 //        buttonClass     : 'pic-link',
	// 	buttonText		: '上传头像',
	// 	fileObjName		: 'userfile',
	// 	fileSizeLimit	: '2MB',
	// 	fileTypeExts	: '*.jpg;*.png;*.gif;',		
	// 	onSelect : function(fileObj) {
	// 		$("#teacherphoto1").attr('src', KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif');
	// 	},		
	// 	onUploadSuccess : function(file, data, response) {
	// 		data = eval('('+data+')');
	// 		if(data.error == 0){
	// 			$("#teacherphoto1").attr('src', data.url);
	// 			$("#teacherphoto1").attr('val', data.url);
	// 		}else{
	// 			alert(data.message);
	// 		}
	// 	}
 //    });
	
	// $("#uploadTeacher2").uploadify3({
 //        height			: '30',
 //        swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
 //        uploader		: KK._uploadImgUrl+"/?sid="+SID+"&type=2&json=1",
 //        width			: '128',
 //        buttonCursor	: '',
 //        buttonClass     : 'pic-link',
	// 	buttonText		: '上传头像',
	// 	fileObjName		: 'userfile',
	// 	fileSizeLimit	: '2MB',
	// 	fileTypeExts	: '*.jpg;*.png;*.gif;',		
	// 	onSelect : function(fileObj) {
	// 		$("#teacherphoto2").attr('src', KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif');
	// 	},		
	// 	onUploadSuccess : function(file, data, response) {
	// 		data = eval('('+data+')');
	// 		if(data.error == 0){
	// 			$("#teacherphoto2").attr('src', data.url);
	// 			$("#teacherphoto2").attr('val', data.url);
	// 		}else{
	// 			alert(data.message);
	// 		}
	// 	}
 //    });
	
	// $("#uploadTeacher3").uploadify3({
 //        height			: '30',
 //        swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
 //        uploader		: KK._uploadImgUrl+"/?sid="+SID+"&type=2&json=1",
 //        width			: '128',
 //        buttonCursor	: '',
 //        buttonClass     : 'pic-link',
	// 	buttonText		: '上传头像',
	// 	fileObjName		: 'userfile',
	// 	fileSizeLimit	: '2MB',
	// 	fileTypeExts	: '*.jpg;*.png;*.gif;',		
	// 	onSelect : function(fileObj) {
	// 		$("#teacherphoto3").attr('src', KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif');
	// 	},		
	// 	onUploadSuccess : function(file, data, response) {
	// 		data = eval('('+data+')');
	// 		if(data.error == 0){
	// 			$("#teacherphoto3").attr('src', data.url);
	// 			$("#teacherphoto3").attr('val', data.url);
	// 		}else{
	// 			alert(data.message);
	// 		}
	// 	}
 //    });
	
	// $("#uploadTeacher4").uploadify3({
 //        height			: '30',
 //        swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
 //        uploader		: KK._uploadImgUrl+"/?sid="+SID+"&type=2&json=1",
 //        width			: '128',
 //        buttonCursor	: '',
 //        buttonClass     : 'pic-link',
	// 	buttonText		: '上传头像',
	// 	fileObjName		: 'userfile',
	// 	fileSizeLimit	: '2MB',
	// 	fileTypeExts	: '*.jpg;*.png;*.gif;',		
	// 	onSelect : function(fileObj) {
	// 		$("#teacherphoto4").attr('src', KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif');
	// 	},		
	// 	onUploadSuccess : function(file, data, response) {
	// 		data = eval('('+data+')');
	// 		if(data.error == 0){
	// 			$("#teacherphoto4").attr('src', data.url);
	// 			$("#teacherphoto4").attr('val', data.url);
	// 		}else{
	// 			alert(data.message);
	// 		}
	// 	}
 //    });
	
	// $("#uploadTeacher5").uploadify3({
 //        height			: '30',
 //        swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
 //        uploader		: KK._uploadImgUrl+"/?sid="+SID+"&type=2&json=1",
 //        width			: '128',
 //        buttonCursor	: '',
 //        buttonClass     : 'pic-link',
	// 	buttonText		: '上传头像',
	// 	fileObjName		: 'userfile',
	// 	fileSizeLimit	: '2MB',
	// 	fileTypeExts	: '*.jpg;*.png;*.gif;',		
	// 	onSelect : function(fileObj) {
	// 		$("#teacherphoto5").attr('src', KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif');
	// 	},		
	// 	onUploadSuccess : function(file, data, response) {
	// 		data = eval('('+data+')');
	// 		if(data.error == 0){
	// 			$("#teacherphoto5").attr('src', data.url);
	// 			$("#teacherphoto5").attr('val', data.url);
	// 		}else{
	// 			alert(data.message);
	// 		}
	// 	}
 //    });
	
	$("#addCoverPic").click(function(){
		if(IsAuthorize > 0){
			var url = "/?mod=course&act=create&do=coverPic&authorize=1&sid="+SID+"&random="+Math.random();
		}else{
			var url = "/?mod=course&act=create&do=coverPic&random="+Math.random();
		}
		var uploadBoxy = $.ckAjaxBoxy({
			url : url,
			title : "上传图片",
			width : 632,
			height : 597,
			callback : function(){
				$("#uploadCover").uploadify3({
			        height			: '30',
			        swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
			        uploader		: KK._uploadImgUrl+"/?sid="+SID+"&type=1&json=1",
			        width			: '81',
			        buttonCursor	: 'hand',
			        buttonClass     : 'c_btn30',
					buttonText		: '上传图片',
					fileObjName		: 'userfile',
					fileSizeLimit	: '2MB',
					fileTypeExts	: '*.jpg;*.png;*.gif;',
					
					onSelect : function(fileObj) {
						$("#coverPic").html('<img src="'+KK._resurl+'/sites/www/v2/images/public/dialog/loading.gif" class="loadingImg" width="" height="" />');
					},
					
					onUploadSuccess : function(file, data, response) {
						data = eval('('+data+')');
						if(data.error == 0){
							$("#coverPic").html("<img src='"+data.url+"' />");
							$("#coverPicSubmit").unbind().bind('click', function(){
								if($("#addCoverPic").prev('img').length > 0){
									$("#addCoverPic").prev('img').attr('src', data.url);
								}else{
									$("#addCoverPic").before('<img width="120" heihgt="90" alt="" src="'+data.url+'" class="fl mr5">');
								}
								$("#addCoverPic span").text('更改图片');
								$("#cover").val(data.url);
								uploadBoxy.cancel();
								checkCover();
							});
						}else{
							alert(data.message);
						}
					}
			    });
				$("#coverPicCancel").click(function(){
					uploadBoxy.cancel();
					checkCover();
				});
			}
		});
		return false;
	});
	
	//课程名称
	$("input[name='name']").focus(function(){
		showMessageTip('name', '请填写课程名称，2-30个汉字或者4-60个字符', 'notice');
	}).blur(function(){
		checkCourseName();
	});
	
	//课程价格
	$("input[name='cost']").focus(function(){
		showMessageTip('cost', '请填写课程价格，0.00-1,000,000.00之间，如：10,20.00', 'notice');
	}).blur(function(){
		checkCost();
	});
	
	//单课
	$("#singlePrice").focus(function(){
		showMessageTip('singlePrice', '请填写课程价格，0.00-1,000,000.00之间，如：10,20.00', 'notice');
	}).blur(function(){
		checkSingleBuy();
	});
	
	//课时数
	$("input[name='hours']").focus(function(){
		showMessageTip('hours', '请填写总课时，1-1000的整数，如：60', 'notice');
	}).blur(function(){
		checkCourseHours();
	});
	
	$("input[name='expiretime']").focus(function(){
		showMessageTip('expiretime', '请填有效期天数，30-3650的整数，如：60', 'notice');
	}).blur(function(){
		checkExpireTime();
	});
	
	//时间选择
	$("input[name='payendtime']").focus(function(){
		showMessageTip('payendtime', '请选择课程结束时间', 'notice');
	}).blur(function(){
		checkPayEndTime();
	});
	
	//报名人数限制
	$("input[name='studentlimit']").focus(function(){
		showMessageTip('studentlimit', '请填写购买人数限制，1-1000000的整数，如：10000', 'notice');
	}).blur(function(){
		checkStudentLimit();
	});
	
	//教室容量
	$("input[name='classroomcapacity']").focus(function(){
		showMessageTip('classroomcapacity', '请填写1-'+ClassroomLimit+'之间的整数', 'notice');
	}).blur(function(){
		checkClassroomCapacity();
	});
    
    //初始化select控件
    if (typeof custom_type != 'undefined') {
	    $("#customParentType").divSelect('200');
	    if ($("#customParentType").val() != 0) {
	    	initCustomSubType($("#customParentType").val());
	    } else {
	    	$("#customSubType").divSelect('200');
	    }
	    
	    $("#customParentType").change(function(){
	    	var parentId = $(this).val();
	    	if (parentId == 0) {
	    		$("#customSubType").html('<option value="0">- 选择二级分类 -</option>').divSelect('200');
	    		return false;
	    	}
	    	if(typeof custom_type[parentId].SubType != "undefined"){
	    		initCustomSubType(parentId);
	    	}else{
	    		$("#customSubType").html('<option value="0">- 选择二级分类 -</option>').divSelect('200');
	    		return false;
	    	}
	    });
    }
    
    // if(CacheParentType != '' && CacheParentType != 0){
    // 	$("#customParentType").val(CacheParentType);
    // 	$("#customParentType").divSelect('200');
    // }
    
    // if(CacheSubType != '' && CacheSubType != 0){
    // 	initCustomSubType(CacheParentType);
    // 	$("#customSubType").val(CacheSubType);
    // 	$("#customSubType").divSelect('200');
    // }
    
    //担保期
    $("#vodExpires").focus(function(){
    	showMessageTip('vodExpires', '需为15-500的整数', 'notice');
    }).blur(function(){
    	checkVodExpires();
    });
    
    var editFinishButton = false;
    $("a.editFinish").click(function(){
    	editFinishButton = true;
    	$("a.submit").trigger('click');
    	return false;
    });
    
    $("a.submit").click(function(){
    	editor.sync();
    	if(checkCourseName() === false){
    		ErrorShine($("#name"));
    		return false;
    	}else if(checkCost() === false){
    		ErrorShine($("#cost"));
    		return false;
    	}else if(checkCourseHours() === false){
    		ErrorShine($("#hours"));
    		return false;
    	}else if(checkExpireTime() === false){
    		ErrorShine($("#expiretime"));
    		return false;
    	}else if(checkPayEndTime() === false){
    		ErrorShine($("#payendtime"));
    		return false;
    	}else if(checkStudentLimit() === false){
    		ErrorShine($("#studentlimit"));
    		//$("#studentlimit").focus();
    		return false;
    	}else if(checkClassroomCapacity() === false){
    		ErrorShine($("#classroomcapacity"));
    		//$("#classroomcapacity").focus();
    		return false;
    	}else if(checkBrief() === false){
    		//editor.focus();
    		return false;
    	}else if(checkCover() === false){
    		return false;
    	}else if(checkVodExpires() === false){
    		ErrorShine($("#vodExpires"));
    		//$("#vodExpires").focus();
    		return false;
    	}else if(checkSingleBuy() === false){
    		ErrorShine($("#singlePrice"));
    		return false;
    	}else if(checkPeople() === false){
    		ErrorShine($("#people"));
    		return false;
    	}else if(checkKnowledge() === false){
    		ErrorShine($("#knowledge"));
    		return false;
    	}
		var teacherPostArr = checkCourseTeacher();
		if(teacherPostArr === false){
    		return false;
    	}
		
    	
    	var name = $("#name").val(),
            cost = $("#cost").val(),
            cateid = $("#cateid").val(),
            hours = $("#hours").val(),
            expiretime = $("#expiretime").val(),
            payendtime = $("#payendtime").val(),
            studentlimit = $("#studentlimit").val(),
            classroomcapacity = $("#classroomcapacity").val(),
            brief = $("#brief").val(),
            cover = $("#cover").val(),
            customSubType = $("#customSubType").val(),
            customParentType = $("#customParentType").val(),
            vodExpires = $("#vodExpires").val(),
            customType = typeof(customSubType) == 'undefined' ? false : customSubType,
            customType = customType != false ? customType : customParentType,
    	    singleBuy = $("input:radio[name='singleBuy']:checked").val(),
            singlePrice = singleBuy == 2 ? $("#singlePrice").val() : '',
            individuation = $("input:radio[name='individuation']:checked").val(),
            individuation = typeof(individuation) == 'undefined' ? 0 : individuation;
               
        if (individuation == 1) {
            singleBuy = 1;
            singlePrice = '';
        }

    	var postDataStr = ["name="+encodeURIComponent(name),
    	                   "cost="+encodeURIComponent(cost),
    	                   "cateid="+encodeURIComponent(cateid),
    	                   "hours="+encodeURIComponent(hours),
    	                   "expiretime="+encodeURIComponent(expiretime),
    	                   "payendtime="+encodeURIComponent(payendtime),
    	                   parseInt(studentlimit) > 0 ? "studentlimit="+encodeURIComponent(studentlimit) : "",
    	                   "classroomcapacity="+encodeURIComponent(classroomcapacity),
    	                   "brief="+encodeURIComponent(brief),
    	                   "cover="+encodeURIComponent(cover),
    	                   customType != false ? "customType="+encodeURIComponent(customType) : "",
    	                   parseInt(vodExpires) > 0 ? "vodExpires="+encodeURIComponent(vodExpires) : "",
    	                   "singleBuy="+encodeURIComponent(singleBuy),
    	                   "singlePrice="+encodeURIComponent(singlePrice),
    	                   "individuation="+encodeURIComponent(individuation)].join('&');
    	 
    	var degree = $('input[name="degree"]:checked ').val(),
			people = $('#people').val(),
    		knowledge = $('#knowledge').val();
        var postAddDataStr = '';
		if(degree != ''){
			postAddDataStr += "degree="+encodeURIComponent(degree)+'&';
		}
    	if(people != ''){
    		postAddDataStr += "people="+encodeURIComponent(people)+'&';
    	}
    	if(knowledge != ''){
    		postAddDataStr += "knowledge="+encodeURIComponent(knowledge)+'&';
    	}
		if(teacherPostArr != ''){
			postAddDataStr += teacherPostArr
		}
		if(postAddDataStr != ''){
			postDataStr += '&'+postAddDataStr;
		}
		
    	var publishTag = "";
    	if($(this).attr('type') == "publish"){
    		publishTag = "&onsell=1";
    	}
    	
    	if(CourseID === false){
    		if(IsAuthorize > 0){  			
    			var url = "/?mod=course&act=create&do=basicSave"+publishTag+"&authorize=1&sid="+SID+"&random="+Math.random();
    		}else{
    			var url = "/?mod=course&act=create&do=basicSave"+publishTag+"&random="+Math.random();
    		}	
    	}else{
    		if(IsAuthorize > 0){
    			if(IsRecreate){
    				var url = "/?mod=course&act=edit&do=recreate&authorize=1&sid="+SID+"&courseid="+CourseID+"&random="+Math.random();
    			}else{
    				var url = "/?mod=course&act=edit&do=basicSave&authorize=1&sid="+SID+"&courseid="+CourseID+"&random="+Math.random();
    			}
    		}else{
    			if(IsRecreate){
    				var url = "/?mod=course&act=edit&do=recreate&courseid="+CourseID+"&random="+Math.random();
    			}else{
    				var url = "/?mod=course&act=edit&do=basicSave&courseid="+CourseID+"&random="+Math.random();
    			}
    		}
    	}
    	if((SchoolTrialStatus == 1) && (cost > 0)){
    		$.ckAlert({message : "试用期学校不能发布付费课程"});
    	} else {  	
	    	if(parseInt(studentlimit) > parseInt(classroomcapacity)){
	    		var tipsBoxy = false;
	    		$.ckConfirm({
	    			message : "你设定的限购人数大于直播教室的容量，当购买人数超过教室容量时，存在某些用户无法进入教室的风险",
	    			width : 450,
	    			ok : function(){
	    				$.ajax({
	    		    		url : url,
	    		    		type : "post",
	    		    		data : postDataStr,
	    		    		async : true,
	    		    		dataType : "json",
	    		    		beforeSend : function(){
	    		    			tipsBoxy = $.ckTipsBoxy({
	    		    				type : "loading",
	    		    				message : "保存中...",
	    		    				mask : true,
	    		    				width : 350
	    		    			});
	    		    		},
	    		    		success : function(rs){
	    		    			if(rs.code < 0){
	    		    				tipsBoxy.cancel();
	    		    				switch(rs.code){
	    		    					case -1 : ErrorShine($("#name"));break;
	    		    					case -2 : ErrorShine($("#cost"));break;
	    		    					case -3 : $.ckTipsBoxy({message : "请选择课程分类",type:"error"});break;
	    		    					case -4 : ErrorShine($("#hours"));break;
	    		    					case -5 : ErrorShine($("#studentlimit"));break;
	    		    					case -6 : ErrorShine($("#classroomcapacity"));break;
	    		    					case -7 : editor.focus();break;
	    		    					case -8 : $.ckTipsBoxy({message : "请添加课程封面",type:"error"});break;
	    		    					case -9 : 
	    		    						if(rs.data != ''){
	    		    							$.ckTipsBoxy({
	    		    								type : "error",
	    		    								message : rs.data,
	    		    								width : 300,
	    		    								mask : true,
	    		    								callback : function(){
	    		    									$("#vodExpires").focus();
	    		    								}
	    		    							});
	    		    						}else{
	    		    							ErrorShine($("#vodExpires"));
	    		    						}
	    		    						break;
	    		    					case -10 : 
	    		    						if(rs.data != ''){
	    		    							$.ckTipsBoxy({
	    		    								type : "error",
	    		    								message : rs.data,
	    		    								width : 300,
	    		    								mask : true,
	    		    								callback : function(){
	    		    									$("#payendtime").focus();
	    		    								}
	    		    							});
	    		    						}else{
	    		    							ErrorShine($("#payendtime"));
	    		    						}
	    		    						break;
	    		    					case -11 : 
	    		    						ErrorShine($("#singlePrice"));
	    		    						break;
	    		    					case -12:
	    		    						ErrorShine($("#expiretime"));
	    		    						break;
	    		    					case -13:
	    		    						$.ckTipsBoxy({
	    										type : "error",
	    										width : 500,
	    										message : '不能添加外部链接，请删除后再提交！'
	    									});
	    		    						break;
	    		    					default : $.ckTipsBoxy({
			    								type : "error",
			    								width : 300,
			    								message : rs.data
			    							});
	    		    				}
	    		    			}else{
	    		    				if(CourseID === false){
	    		    					if(IsAuthorize > 0){
		    		    					$.ckTipsBoxy({
		    		    						type : "success",
		    		    						message : "保存成功",
		    		    						callback : function(){
		    	    		    					document.location = "/?mod=course&act=create&do=detail&authorize=1&sid="+SID+"&courseid="+rs.code;
		    		    						}
		    		    					});
	    		    					}else{
	    		    						document.location = rs.data;
	    		    					}
	    		    				}else{
	    		    					if(IsRecreate){
		    								document.location = "/?mod=course&act=create&&do=aftersave&courseid="+rs.code+"&sid="+SID+"&onsell=1";
		    							}else{
		    		    					$.ckTipsBoxy({
		    		    						type : "success",
		    		    						message : "保存成功",
		    		    						callback : function(){
		    		    							window.scroll(0,0);
		    		    							if(editFinishButton){
		    		    								document.location = "/?mod=course&act=edit&&do=editFinish&courseid="+CourseID;
		    		    							}
		    		    						}
		    		    					});
	    		    					}
	    		    				}
	    		    			}
	    		    		}
	    		    	});
	    			}
	    		})
	    	}else{
	    		var tipsBoxy = false;
	    		$.ajax({
		    		url : url,
		    		type : "post",
		    		data : postDataStr,
		    		async : true,
		    		dataType : "json",
		    		beforeSend : function(){
		    			tipsBoxy = $.ckTipsBoxy({
		    				type : "loading",
		    				message : "保存中...",
		    				mask : true,
		    				width : 350
		    			});
		    		},
		    		success : function(rs){
		    			if(rs.code < 0){
		    				tipsBoxy.cancel();
		    				switch(rs.code){
		    					case -1 : ErrorShine($("#name"));break;
		    					case -2 : ErrorShine($("#cost"));break;
		    					case -3 : $.ckTipsBoxy({message : "请选择课程分类",type:"error"});break;
		    					case -4 : ErrorShine($("#hours"));break;
		    					case -5 : ErrorShine($("#studentlimit"));break;
		    					case -6 : ErrorShine($("#classroomcapacity"));break;
		    					case -7 : editor.focus();break;
		    					case -8 : $.ckTipsBoxy({message : "请添加课程封面",type:"error"});break;
		    					case -9 : 
		    						if(rs.data != ''){
		    							$.ckTipsBoxy({
		    								type : "error",
		    								message : rs.data,
		    								width : 300,
		    								mask : true,
		    								callback : function(){
		    									$("#vodExpires").focus();
		    								}
		    							});
		    						}else{
		    							ErrorShine($("#vodExpires"));
		    						}
		    						break;
		    					case -10 : 
		    						if(rs.data != ''){
		    							$.ckTipsBoxy({
		    								type : "error",
		    								message : rs.data,
		    								width : 300,
		    								mask : true,
		    								callback : function(){
		    									$("#expiretime").focus();
		    								}
		    							});
		    						}else{
		    							ErrorShine($("#expiretime"));
		    						}
		    						break;
		    					case -11 : 
		    						ErrorShine($("#singlePrice"));
		    						break;
		    					case -12:
		    						ErrorShine($("#expiretime"));
		    						break;
		    					case -13:
		    						$.ckTipsBoxy({
										type : "error",
										width : 500,
										message : '不能添加外部链接，请删除后再提交！'
									});
		    						break;
		    					default :$.ckTipsBoxy({
									type : "error",
									width : 300,
									message : rs.data
								});
		    				}
		    			}else{
		    				if(CourseID === false){
		    					if(IsAuthorize > 0){
			    					$.ckTipsBoxy({
			    						type : "success",
			    						message : "保存成功",
			    						callback : function(){
		    		    					document.location = "/?mod=course&act=create&do=detail&authorize=1&sid="+SID+"&courseid="+rs.code;
			    						}
			    					});
		    					}else{
		    						document.location = rs.data;
		    					}
		    				}else{
		    					if(IsRecreate){
									document.location = "/?mod=course&act=create&&do=aftersave&courseid="+rs.code+"&sid="+SID+"&onsell=1";
								}else{
			    					$.ckTipsBoxy({
			    						type : "success",
			    						message : "保存成功",
			    						callback : function(){
			    							window.scroll(0,0);
			    							if(editFinishButton){
			    								document.location = "/?mod=course&act=edit&&do=editFinish&courseid="+CourseID;
			    							}
			    						}
			    					});
								}
		    				}
		    			}
		    		}
		    	});
	    	} 
    	}
    	return false;
    });
});

function initCustomSubType(parentId) {
	if (typeof custom_type != 'undefined') {
		var type_list = custom_type[parentId].SubType;
		var options = '';
		$.each(type_list, function(i, val){
			options += '<option value="'+val.TypeID+'">'+val.Name+'</option>';
		});
		$("#customSubType").html(options).divSelect('200');
	}
}